<template>
    <div class="e-form">
        <BillTop title="报废处置登记详情" @cancel="handleClose"></BillTop>
        <div class="tabs">
            <el-tabs tab-position="left" v-model="tabsName" @tab-click="onChangeTab">
                <!-- 基本信息 -->
                <el-tab-pane label="基本信息" name="baseInfo" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="残值记录信息" name="planDetail" :disabled="clickTabFlag"></el-tab-pane>
                <el-tab-pane label="附件信息" name="attach" :disabled="clickTabFlag"></el-tab-pane>
                <div>
                    <div id="baseInfoCon">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form ref="form" :model="formData.scrapRegister" label-width="200px">
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="记录编号：">
                                            <span>{{ formData.scrapRegister.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="处置结算编号：">
                                            <span>{{ formData.scrapRegister.disposeNum }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="记录日期：">
                                            <span>{{ formData.scrapRegister.recordTime  }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="总残值：">
                                            <span>{{ formData.scrapRegister.totalCruel }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ formData.scrapRegister.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="记录人：">
                                            <span>{{ formData.scrapRegister.recordPerson }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item  label="备注：">
                                            <span>{{ formData.scrapRegister.info }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>

                    <div id="planDetailCon">
                        <div class="tabs-title" id="planDetail">残值记录信息</div>
                        <div class="e-table">
                            <el-table
                                :max-height="$store.state.tableHeight"
                                class="table"
                                ref="planTable"
                                :data="scrapRegisterDtlList"
                                border
                                style="width: 100%"
                                @selection-change="planTableSelect"
                                v-sortTable="{ 'tableData': scrapRegisterDtlList, '_this': this, 'ref': 'planTable' }"
                            >
                                <!-- <el-table-column type="selection" width="55" align="center">
                                </el-table-column> -->
                                <el-table-column
                                    prop="equipmentNo"
                                    label="设备编号"
                                    align="center"
                                    min-width="200"
                                    show-overflow-tooltip
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentName"
                                    label="设备名称"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="specificationModel"
                                    label="规格型号"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="buyTime"
                                    label="购置日期"
                                    min-width="200"
                                    show-overflow-tooltip
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="originalPrice"
                                    label="设备原值（元）"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="formerPrice"
                                    label="累计折旧（元）"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="equipmentValue"
                                    label="设备净值（元）"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="stipulateTime"
                                    label="规划使用年限"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="alreadyTime"
                                    label="已使用年限"
                                    width="150"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="scrapType"
                                    label="报废类型"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.scrapType ? scrapTypeList.find(x=>x.value === row.scrapType).label : '' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="processMode"
                                    label="处置方式"
                                    width="200"
                                    align="center"
                                >
                                    <template slot-scope="{ row }">
                                        <span>{{ row.processMode ? processModeList.find(x=>x.value === row.processMode).label : '' }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="realityScrapValue"
                                    label="实际回收残值"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="evaluateUnit"
                                    label="评估单位"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="evaluatePrice"
                                    label="评估价（元）"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="presentPlace"
                                    label="设备当前所在地"
                                    width="200"
                                    align="center"
                                >
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>

                    <div id="attachCon">
                        <div class="tabs-title" id="attach">附件信息</div>
                        <attach-comp :relationId="attachId" isView bucketName="facilitymanagement" />
                    </div>

                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <el-button type="primary" size="small" class="btn-blue"
            v-debounce
                >打印</el-button
            >
            <el-button size="small" @click="handleClose" v-debounce>取消</el-button>
        </div>
        <div id="seat" :style="{height: seatHeight + 'px'}"></div>
    </div>
</template>

<script>
import { mapState, mapMutations } from 'vuex'
import $ from 'jquery'
import request from '@/api/equip/dailyManagement.js'
import '@/utils/jquery.scrollTo.min'
import AttachComp from '@/components/common/attachIndex'
import { hideLoading, showLoading } from '@/utils/common'
export default {
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            selectEquipVisible: false,
            formData: {
                //基础信息
                'scrapRegister': {
                    'billId': '',
                    'billNo': '',
                    'disposeNum': '',
                    'founderId': '',
                    'founderName': '',
                    'info': '',
                    'orgId': '',
                    'orgName': '',
                    'recordPerson': '',
                    'recordPersonId': '',
                    'recordTime': '',
                    'state': 0,
                    'totalCruel': 0
                },
            },
            billid: this.$route.query.billid,
            planSelect: [], //残值记录信息选择项
            scrapRegisterDtlList: [],
            workIndex: 0,
        }
    },
    computed: {
        ...mapState({
            userInfo: state => state.userInfo,
            scrapTypeList: state => state.equip.equipData.scrapTypeList, //报废类型
            processModeList: state => state.equip.equipData.processModeList, //处置方式
        }),
        statusLable () {
            return param=> {
                const state =  this.$store.state.equip.equipData.state
                const obj = state.find(x=>x.value === param)
                return obj.label
            }
        },
        //当前单据状态
        state () {
            return this.formData.scrapRegister.state
        },
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.$route.query.billid
        }
    },
    components: {
        AttachComp
    },
    created () {
        this.userId = localStorage.getItem('userId')
        this.init()
    },
    mounted () {
        // 获取最后一个内容区域的高度，计算底部空白
        this.getLastConHeight()

        // 保存所有tabName
        const arr = ['baseInfo', 'planDetail', 'attach']
        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    console.log('item', item)
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop = document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if ((scrollTop + 1) >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
    },
    methods: {
        ...mapMutations(['setAuditParams']),
        init () {
            showLoading()
            Promise.all([
                this.getInfo(),
                this.getPlanList(),
                this.getAuditHistory(),
            ]).finally(() => {
                hideLoading()
            })
        },
        getInfo () {
            const params = {
                billId: this.billid,
                id: this.billid
            }
            request.scrapDisposalBaseInfo(params).then(res=>{
                this.formData.scrapRegister = res.scrapRegister
            })
        },
        getPlanList () {
            const params = {
                id: this.billid,
            }
            request.scrapDisposalPlanInfo(params).then(res=>{
                this.scrapRegisterDtlList = res.scrapRegisterDtlList
            })
        },
        //取消
        handleClose () {
            this.$router.replace('/scrapDisposalList')
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight = document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
    }
}
</script>

<style lang="scss" scoped>
.form {
    margin-top: 10px;
}

.e-table {
    background: #fff;
}

</style>
